/*
 * LiveMediaPlayer.cpp
 *
 *  Created on: 2018年8月2日
 *      Author: zhengboyuan
 */
#include "stdafx.h"
#include "LiveMediaPlayer.h"
#include "TStringUtil.h"


int	LiveMediaPlayer::MAX_DELAY_TIME = 1000 * 3;


LiveMediaPlayer::LiveMediaPlayer():
    m_devID(),
    m_faceTrackEnabled(),
	m_faceCount()
{
}

LiveMediaPlayer::~LiveMediaPlayer()
{
    Close();
}

bool LiveMediaPlayer::Open(nvs::NetVideoSystem* system, const char* devID)
{
    if (!system || !devID)
    {
        return false;
    }

    m_devID = devID;

    nvs::MediaStream* stream = NULL;
    int ret = system->openLiveStream(devID, 0, &stream);
    if (ret != nvs::NVS_ERR_OK)
    {
        return false;
    }

    return MediaStreamPlayer::Open(system, stream);
}

bool LiveMediaPlayer::CanSeek()
{
    return false;
}

std::string LiveMediaPlayer::GetUrl()
{
    return m_devID;
}

void LiveMediaPlayer::EnableDrawTrack(bool enabled)
{
	comn::AutoCritSec lock(m_cs);
    m_faceTrackEnabled = enabled;

	if (IsOpen())
	{
		MDecode_SetDelayTime(m_handle, MAX_DELAY_TIME);
	}
}

void LiveMediaPlayer::decodeCallback(HANDLE handle, MDecode_Frame* frame, void* pUser)
{
	LiveMediaPlayer* pthis = (LiveMediaPlayer*)pUser;
	pthis->onDecodeFrame(handle, frame);
}

void LiveMediaPlayer::onDecodeFrame(HANDLE handle, MDecode_Frame* frame)
{
	// pass
}

std::string LiveMediaPlayer::makeFaceTrack(int width, int height, int64_t pts)
{
	int xStep = (m_faceCount % 16) * 10;
	int yStep = (m_faceCount % 9) * 10;

	int x1 = 50 + xStep;
	int y1 = 50 + yStep;
	int x2 = 200 + xStep;
	int y2 = 200 + yStep;

	int rx = 40 + xStep;
	int ry = 40 + yStep;

	std::string text = comn::StringUtil::format(
		"{\"channel_id\":\"2200001201000501\",\"frame_id\":\"%lld\",\"line_color\":\"00ff00\",\"line_size\":2,\"font_size\":20,\"font_type\":0,\"font_color\":\"aa00aa\",\"face_rec\":[{\"x1\":%d,\"y1\":%d,\"x2\":%d,\"y2\":%d,\"remark\":\"0/0/1\",\"remark_pointX\":%d,\"remark_pointY\":%d}, {\"x1\":400,\"y1\":200,\"x2\":500,\"y2\":400,\"remark\":\"1/1/2\",\"remark_pointX\":400,\"remark_pointY\":160}]}",
		pts, x1, y1, x2, y2, rx, ry);
	return text;
}

void LiveMediaPlayer::onOpen()
{
	MediaStreamPlayer::onOpen();

	//MDecode_SetDecodeCallback(m_handle, MDECODE_PIXEL_BGR24, decodeCallback, this);
	if (m_faceTrackEnabled)
	{
		MDecode_SetDelayTime(m_handle, MAX_DELAY_TIME);
	}

	MDecode_SetParam(m_handle, "video.show_frame", "1");
}

void LiveMediaPlayer::inputFaceTrack(const char* devID, const char* text, int size)
{
	if (!text || size <= 0)
	{
		return;
	}

	m_faceCount ++;

	std::string src(text, size);
	std::string fid = comn::StringUtil::extract(src, 0, "frame_id\":", ",", true);
	comn::StringUtil::trim(fid, ":\" ");

	TRACE("live track: %s\n", src.c_str());
	TRACE("live frame_id: %s\n", fid.c_str());
	
	int64_t pts = 0;
	comn::StringCast::toValue(fid, pts);

	MDecode_InputData(m_handle, MDECODE_MEDIA_SUBTITLE, (const uint8_t*)text, size, pts, 0);
}